package com.xiaoxi.exam.service;

import cn.xinzhili.xutils.core.FailureException;
import cn.xinzhili.xutils.core.http.Response;
import com.xiaoxi.exam.bean.enums.AccountCheckStatus;
import com.xiaoxi.exam.bean.enums.ExamType;
import com.xiaoxi.exam.bean.errorcode.UserErrorCode;
import com.xiaoxi.exam.bean.request.RegisterExamRequest;
import com.xiaoxi.exam.bean.sync.UserInfo;
import com.xiaoxi.exam.dao.AccountMapper;
import com.xiaoxi.exam.model.Account;
import com.xiaoxi.exam.model.AccountExample;
import com.xiaoxi.exam.model.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AccountService {

  @Autowired
  private AccountMapper accountMapper;

  @Autowired
  private UserService userService;

  @Value("${ocr.url:http://192.168.1.200:8000/ocr/}")
  private String ocrUrl;

  public Response addAccount(RegisterExamRequest request) {
    User userInfo = userService.getUserInfo(request.getOpenId());
    if (Objects.isNull(userInfo)) {
      throw new FailureException(UserErrorCode.USER_NOT_EXIST);
    }
    addUserAccount(userInfo.getId(), request.getUserAccount(), request.getPassword(),
        request.getType());
    UserInfo userInfo1 = new UserInfo();
    userInfo1.setUserId(userInfo.getId());
    userInfo1.setTel(userInfo.getTel());
    userInfo1.setAccount(request.getUserAccount());
    userInfo1.setPasswd(request.getPassword());
//    syncService.syncUser(userInfo1);
    return Response.instanceSuccess();
  }

  private void addUserAccount(long userId, String account, String password, ExamType type) {
    AccountExample example = new AccountExample();
    example.createCriteria().andUserIdEqualTo(userId);
    accountMapper.deleteByExample(example);
    Account accountData = new Account();
    accountData.setUserId(userId);
    accountData.setAccount(account);
    accountData.setPassword(password);
    accountData.setType(type);
    accountData.setStatus(AccountCheckStatus.WAITING);
    accountMapper.insert(accountData);
  }

  public Account getAccountByUserId(long userId) {
    AccountExample example = new AccountExample();
    List<AccountCheckStatus> statuses = new ArrayList<>();
    statuses.add(AccountCheckStatus.SUCCESS);
    statuses.add(AccountCheckStatus.WAITING);
    example.or().andUserIdEqualTo(userId).andStatusIn(statuses).andDeletedAtIsNull();
    example.setOrderByClause("created_at desc");
    List<Account> accounts = accountMapper.selectByExample(example);
    if (accounts.isEmpty()) {
      return null;
    } else {
      return accounts.get(0);
    }
  }
}
